package 力扣;

import sun.plugin2.util.NativeLibLoader;

/**
 * @author yyq
 * @create 2022-04-19 20:28
 */
public class leetcode450 {
    public TreeNode deleteNode(TreeNode root, int key) {
        if(root==null) return null;
        if(root.val==key){
            if(root.left==null&&root.right==null)
                return null;
        }
        TreeNode temp =null;
        temp = preOrder(null,root,key);
        if(temp!=null) return temp;
        return root;

    }

    private TreeNode preOrder(TreeNode pre, TreeNode root, int key) {
        TreeNode temp = null;

        if(root.val == key){

            TreeNode temproot = null;
            TreeNode left=root.left;
            TreeNode right=root.right;
            if(right==null){
                temproot = left;
            }else if(right!=null){
                if(left==null){
                    temproot=right;
                }else{
                    TreeNode righttemp = right;
                    while (righttemp.left!=null){
                        righttemp = righttemp.left;
                    }
                    righttemp.left=left.right;
                    left.right=right;
                    temproot =left;
                }
            }
            if(pre==null){
                return temproot;
            }
            if(pre!=null){
                if(pre.val>root.val){
                    pre.left= temproot;
                }
                if(pre.val<root.val){
                    pre.right=temproot;
                }
            }
        }
        if(root.left!=null) temp = preOrder(root, root.left,key);
        if(temp!=null) return temp;
        if(root.right!=null) temp = preOrder(root, root.right,key);
        if(temp!=null) return temp;
        return temp;
    }
}
